<?php
session_start();
require_once("dbConnect.inc");
require_once("errorhandler.php");
set_error_handler("error_msg");

$databaseConnection = mysqli_connect($hostname, $username, $password, $database);

if (mysqli_connect_errno()) {
    trigger_error("Het is niet gelukt om verbinding te maken met de database.", E_USER_ERROR);
    exit();
}

$admin = (isset($_SESSION["admin"]) AND $_SESSION["admin"] == 1) ? true : false;
$blogid = isset($_SESSION["blogid"]) ? "?id=" . $_SESSION["blogid"] : "";

if (isset($_SESSION["userid"])) {
    $userId = $_SESSION["userid"];
} else {
    exit("Deze bewerking is alleen toegestaan als je bent aangemeld.</BR>"
            . 'Klik <a href="index.php' . $blogid . '">hier</a> om naar de begin pagina te gaan.</BR>');
}

// Rechter menu
$rightMenu = '<BR><INPUT TYPE=button onClick="location.href=\'index.php\'" value=\'Home\'></BR>';

if (isset($_POST["submit"])) {
    $onderwerp = strip_tags($_POST["onderwerp"]);
    // Strip html tags
    $bericht = strip_tags($_POST["bericht"]);
    if (isset($_POST["postid"])) {
        $postId = $_POST["postid"];
        if (isset($_POST["delete"]) AND $_POST["delete"] == "yes") {
            $qPost = "DELETE from posts WHERE id = $postId";
        } else {
            $qPost = "UPDATE posts SET onderwerp = '$onderwerp', bericht = '$bericht' WHERE id = $postId";
        }
    } else {
        $qPost = "INSERT INTO posts (userid, onderwerp, bericht, datum) VALUES "
                . "('$userId', '$onderwerp', '$bericht', CURRENT_TIMESTAMP)";
    }

    $queryResult = mysqli_query($databaseConnection, $qPost);

    if (!$queryResult) {
        trigger_error("Het is niet gelukt om de wijzigingen op te slaan in de database.", E_USER_ERROR);
        exit();
    }
    
    header("Location: index.php" . $blogid);
    
} else {
    if (isset($_GET["id"])) {
        $postId = $_GET["id"];
        $qpost = "Select userid, onderwerp, bericht, datum from posts where id = $postId";
        $hiddenPostId = '<input type="hidden" name="postid" value="' . $postId . '" />';
        $queryResult = mysqli_query($databaseConnection, $qpost);

        if (!$queryResult) {
            trigger_error("Het is niet gelukt om het bericht op te halen uit de database.", E_USER_ERROR);
            exit();
        }

        if (mysqli_num_rows($queryResult) == 1) {
            while ($row = mysqli_fetch_array($queryResult, MYSQLI_ASSOC)) {
                $onderwerp = $row["onderwerp"];
                $bericht = $row["bericht"];
                if ($row["userid"] <> $_SESSION["userid"] AND !$admin) {
                    $readonly = "readonly";
                    $disabled = "disabled";
                    $body = "Je bent niet de eigenaar van deze post.</BR>Je mag deze post niet bewerken.</BR></BR>";
                    $body .= 'Klik <a href="index.php' . $blogid . '">hier</a> om terug te gaan naar de begin pagina.</BR>';
                } else {
                    if (isset($_GET["delete"]) AND $_GET["delete"] == "yes") {
                        $body = createForm($blogid, $hiddenPostId, $onderwerp, $bericht, true);
                    } else {
                        $body = createForm($blogid, $hiddenPostId, $onderwerp, $bericht);
                    }
                }
            }
        } else {
            $body = "Het bericht is niet gevonden in de database.";
        }
        mysqli_free_result($queryResult);
    } else {
        $body = createForm($blogid);
    }
}

function createForm($blogid, $hiddenPostId = "", $subject = "", $message = "", $delete = false) {
    if ($delete) {
        $readonly = "readonly";
        $hiddenDeleteVariable = '<input type="hidden" name="delete" value="yes" />';
        $button = '<INPUT TYPE="submit" name="submit" value="Delete"/>&nbsp&nbsp&nbsp';
        $warning = "</BR>Weet je zeker dat je deze post wilt verwijderen?</BR>";
    } else {
        $readonly = "";
        $hiddenDeleteVariable = "";
        $button = '<INPUT TYPE="submit" name="submit" value="Verstuur"/>&nbsp&nbsp&nbsp';
        $warning = "";
    }

    $body = "</BR><label for='onderwerp'>Onderwerp</label></BR>\n";
    $body .= "<INPUT TYPE='text' name='onderwerp' id='t1' value='$subject' $readonly /></BR>\n";
    $body .= "</BR><label for='bericht'>Bericht</label></BR>\n";
    $body .= "<textarea name='bericht' id='ta1' $readonly >$message</textarea></BR>\n";
    $body .= "$warning</BR>\n";
    $body .= "$button";
    $body .= '<INPUT TYPE=button onClick="location.href=\'index.php' . $blogid . '\'" value="Cancel"/></BR>';
    $body .= $hiddenPostId;
    $body .= $hiddenDeleteVariable;
    return $body;
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/
    TR/html4/strict.dtd">
<HTML>
    <HEAD>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
        <title>Inzendopdracht 051R7</title>
    </HEAD>
    <BODY>
        <FORM ACTION="<?php echo $_SERVER["PHP_SELF"]; ?>" METHOD="POST">
            <DIV id="container">
                <DIV id="header">
                    <h1>Bericht 051R7</h1>
                </DIV>
                <DIV id="leftBar">
                    </BR>
                </DIV>
                <DIV id="content">
                    <?php print($body); ?>
                </DIV>
                <DIV id="rightBar">
                    <?php echo $rightMenu; ?></BR>
                </DIV>
            </DIV>
        </FORM>
    </BODY>
</HTML>